package com.itheima.task.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity //开启Security的自动配置
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启全局方法授权的开关
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //密码加密方式
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()//开启表单登录
            .and()
            .logout()  //开启退出功能
            .and()
            .csrf().disable() //关闭CSRF(跨站请求伪造)策略
            .authorizeRequests()
            .antMatchers("/register").permitAll()    //不登录即可访问
            .anyRequest().authenticated(); //其他请求认证即可访问
    }

    //密码模式下需要在spring容器中配置认证管理器AuthenticationManager对象
    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
